package breeze.pixel.weather.main_view.view;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.navigation.NavigationView;
import com.qweather.sdk.bean.geo.GeoBean;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

import breeze.pixel.weather.App;
import breeze.pixel.weather.BaseView;
import breeze.pixel.weather.R;
import breeze.pixel.weather.aboutapp.view.AboutView;
import breeze.pixel.weather.adapter.weather.AirNowAdapter;
import breeze.pixel.weather.adapter.weather.HourlyAdapter;
import breeze.pixel.weather.adapter.weather.IndicesAdapter;
import breeze.pixel.weather.adapter.weather.MoonAdapter;
import breeze.pixel.weather.adapter.weather.WarnAdapter;
import breeze.pixel.weather.adapter.weather.WeatherNowAdapter;
import breeze.pixel.weather.apps_util.utils.API;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.MDialog;
import breeze.pixel.weather.apps_util.utils.TTSUtils;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.apps_util.utils.appsettings.SettingsStaticData;
import breeze.pixel.weather.apps_util.utils.appsettings.SettingsView;
import breeze.pixel.weather.apps_util.views.AirWidgetView;
import breeze.pixel.weather.apps_util.views.WebActivity;
import breeze.pixel.weather.apps_util.views.mtextview.MTextView;
import breeze.pixel.weather.cityhistory.model.MyDatabaseUtils;
import breeze.pixel.weather.cityhistory.view.CityHistory;
import breeze.pixel.weather.earthquake.view.EarthquakeActivity;
import breeze.pixel.weather.main_view.model.LifeStyleDataAdapter;
import breeze.pixel.weather.main_view.presenter.IMainViewPresenter;
import breeze.pixel.weather.main_view.presenter.MainViewPresenter;
import breeze.pixel.weather.moretool.MoreToolView;
import breeze.pixel.weather.search_city.view.SearchCityView;
import breeze.pixel.weather.service.app_widget.WeatherUtils;
import breeze.pixel.weather.share.view.ShareWeatherView;
import breeze.pixel.weather.typhoon.TyphoonInfoActivity;
import breeze.pixel.weather.weather_forecast.view.WeatherForecastView;
import brz.breeze.app_utils.BAppUpdate;
import brz.breeze.app_utils.BAppUtils;
import brz.breeze.app_utils.BHotFixUtils;
import brz.breeze.tool_utils.Blog;
import brz.breeze.web_utils.BWebUtils;
import io.reactivex.annotations.NonNull;

public class MainView extends BaseView implements IMainView, NavigationView.OnNavigationItemSelectedListener {

    private final Bundle weatherDataBundle = new Bundle();

    @Override
    public void setWeatherNow(WeatherNowAdapter data) {
        try {
            WeatherNowAdapter.NowBean bean = data.getNowBean();
            assert bean != null;
            //储存天气数据
            weatherNowBundle.putString("tem", bean.getTemp() + "℃");
            weatherNowBundle.putString("wind", bean.getWindDir() + bean.getWindScale() + "级");
            weatherNowBundle.putString("icon", bean.getIcon());
            weatherNowBundle.putString("weather", bean.getText());
            //语音播报天气数据
            weatherDataBundle.putString("{{temperature}}", bean.getTemp() + "℃");
            weatherDataBundle.putString("{{wind}}", bean.getWindDir() + bean.getWindScale() + "级");
            weatherDataBundle.putString("{{weather}}", bean.getText());
            weatherDataBundle.putString("{{humidity}}", bean.getHumidity());
            weatherDataBundle.putString("{{windSpeed}}", bean.getWindSpeed());
            //设置天气名称
            main2_weather_Name.setText(bean.getText());
            //设置天气图标
            Bitmap icon = AppToolUtil.getweatherIcon(this, bean.getIcon());
            main2_weather_icon.setImageBitmap(icon);
            //设置天气温度
            int           tem           = Integer.parseInt(bean.getTemp());
            ValueAnimator valueAnimator = ValueAnimator.ofInt(0, tem);
            valueAnimator.setDuration(1000);
            valueAnimator.addUpdateListener(animation -> {
                int temData = (int) animation.getAnimatedValue();
                main2_tem.setText(String.format("%s℃", temData));
            });
            valueAnimator.start();
            //设置风向等
            main2_wind_direct.setText(String.format("%s%s级", bean.getWindDir(), bean.getWindScale()));
            //设置湿度
            main2_wet.setText(String.format("湿度：%s%%", bean.getHumidity()));
            //设置更新时间
            main1_update.setText(String.format("更新时间：%s", data.getUpdateTime()));
            //设置大气压强等
            main2_yaqiang.setText(String.format("压强：%s", bean.getPressure()));
            main2_wind_speed.setText(String.format("风速：%skm/h", bean.getWindSpeed()));
            main2_water_ml.setText(String.format("降水：%s", bean.getPrecip()));
            main2_cansee.setText(String.format("能见度：%s公里", bean.getVis()));
            main2_bodytem_text.setText(String.format("体感温度：%s℃", bean.getFeelsLike()));
            main2_clouds_text.setText(String.format("云量：%s", bean.getCloud()));
            main2_environment_bg.setVisibility(View.VISIBLE);
            tts_stringBuilder.append("天气").append(bean.getText()).append(",温度").append(bean.getTemp()).append("℃,")
                    .append(bean.getWindDir()).append(bean.getWindScale()).append("级");
            if (sets.isHideExtraData()) {
                main2_environment_bg.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            Blog.e(TAG, "设置当前天气数据失败：" + e.toString());
            toast("设置当前天气数据失败：" + e.toString());
        }
    }

    private MyDatabaseUtils databaseUtils;

    @Override
    public void setCityDataInfo(GeoBean data) {
        GeoBean.LocationBean bean = data.getLocationBean().get(0);
        if (bean != null) {
            Calendar calendar = Calendar.getInstance();
            int      week_day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (week_day < 0) {
                week_day = 0;
            }
            tts_stringBuilder.append(bean.getName());
            sets.setDefaultCityName(bean.getName());
            sets.setDefaultCityCode(bean.getId());
            main_week.setText(AppToolUtil._DATE_WEEK[week_day]);
            main_cityName.setText(bean.getName());
            main_toolbar_city_name.setText(bean.getName());
            main_cityId.setText(String.format("城市ID:CN%s", bean.getId()));
            main_upcityName.setText(String.format("上级城市：%s", bean.getAdm2()));
            main_xingzhebgName.setText(String.format("行政省区：%s", bean.getAdm1()));
            main_countryName.setText(String.format("国家名称：%s", bean.getCountry()));
            main_areaTime.setText(String.format("所在时区：%s", bean.getUtcOffset()));
            //获取当前天气
            String cityId = "CN" + bean.getId();
            //储存城市数据
            weatherNowBundle = new Bundle();
            weatherNowBundle.putString("cityName", bean.getName());
            weatherDataBundle.putString("{{city}}", bean.getName());
            weatherNowBundle.putString("cityId", cityId);
            presenter.getCurrentWeather(cityId);
            databaseUtils.addData(bean.getName(), cityId);
            //获取空气质量
            presenter.getAirQuality(cityId);
            //获取生活数据
            presenter.getLifeStyle(cityId);
            //获取天气预警
            presenter.getWeatherWarning(cityId);
            //获取小时预报
            presenter.getHourlyWeather(cityId);
            //获取月相信息
            presenter.getMoonInfo(cityId);
            //更新桌面部件
            WeatherUtils.updateView(null);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        showAppPrivacy();
    }

    private void showAppPrivacy() {
        if (sets.isFirstOpenApp()) {
            MDialog mDialog = new MDialog(this);
            mDialog.setTitle("使用提示");
            mDialog.setCancelable(false);
            mDialog.setMessage(getString(R.string.showPrivacy));
            mDialog.setNavigateBotton("同意协议", () -> {
                sets.haveFirstOpenedApp();
                mDialog.cancel();
            });
            mDialog.setPositiveButton("隐私协议", () -> WebActivity.startActivity(MainView.this, SettingsStaticData._API_HOST + "/pixelweather/Privacy.html"));
            mDialog.setNegativeBotton("用户协议", () -> WebActivity.startActivity(MainView.this, SettingsStaticData._API_HOST + "/pixelweather/UserAgreement.html"));
            mDialog.show();
        }
    }

    private TTSUtils ttsUtils;

    @Override
    public void setAirNowData(AirNowAdapter data) {
        AirNowAdapter.NowBean bean = data.getNowBean();
        LinearLayout          bg   = find(R.id.main2_air_bg);
        if (sets.isHideExtraData()) {
            bg.setVisibility(View.GONE);
        }
        //语音播报
        weatherDataBundle.putString("{{airCategory}}", bean.getCategory());
        main_air_category.setText(String.format("空气质量  %s", bean.getCategory()));
        main_air_aqi.setText(bean.getAqi());
        main_air_aqi.setTextSize(35);
        main_air_pm25.setText(String.format("PM10:%s", bean.getPm10()));
        main_air_no2.setText(String.format("二氧化氮:%s", bean.getNo2()));
        main_air_so2.setText(String.format("二氧化硫:%s", bean.getSo2()));
        main_air_co3.setText(String.format("PM2.5:%s", bean.getPm2p5()));
        main_air_co.setText(String.format("一氧化碳:%s", bean.getCo()));
        airWidgetView.setValue(Integer.parseInt(bean.getAqi()));
        //语音播报
        tts_stringBuilder.append(",空气质量").append(bean.getCategory());
    }

    @Override
    public void setLifeStyleData(IndicesAdapter data) {
        List<IndicesAdapter.DailyBean> datas   = data.getDailyBeans();
        LifeStyleDataAdapter           adapter = new LifeStyleDataAdapter(this, datas);
        GridLayoutManager              manager = new GridLayoutManager(this, 2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == datas.size() - 1 && datas.size() % 2 == 1) {
                    return 2;
                }
                return 1;
            }
        });
        main_lifestyle_recyclerview.setLayoutManager(manager);
        main_lifestyle_recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListner(data1 -> showDialog(MainView.this, data1.getName(), data1.getText()));
    }

    @Override
    public void setWeatherWarning(WarnAdapter data) {
        if (data != null) {
            WarnAdapter.WarningBeanBase bean = data.getBean();
            weather_warning.setVisibility(View.VISIBLE);
            weather_warning.setAlpha(0);
            ObjectAnimator animator = ObjectAnimator.ofFloat(weather_warning, "alpha", 0f, 1f);
            animator.setStartDelay(700);
            animator.start();
            main_warning_text.setText(bean.getTitle());
            tts_stringBuilder.append(bean.getTitle());
            weather_warning.setOnClickListener(v -> showDialog(MainView.this, bean.getTitle(), bean.getText()));
        } else {
            weather_warning.setVisibility(View.GONE);
        }
        //检测版本更新
        if (sets.getCheckNewVersion()) {
            checkNewVersion();
        }
    }

    private void checkNewVersion() {
        BAppUpdate.setOnUpdateListener(App.getContext(), SettingsStaticData._UPDATE_APP_URI, new BAppUpdate.BAppUpdateListener() {
            @Override
            public void haveNewVersion(BAppUpdate.BUpdateMode bUpdateMode) {
                if (sets.getIgnoreVersion() != bUpdateMode.getAppVersion()) {
                    MDialog mDialog = new MDialog(MainView.this);
                    mDialog.setTitle("发现新版本");
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(BAppUtils.getAppVersionName(App.getContext())).append("->").append(bUpdateMode.getAppVersionName());
                    mDialog.setSubTitle(stringBuilder);
                    mDialog.setMessage(bUpdateMode.getUpdateContent());
                    mDialog.setPositiveButton("立即更新", () -> {
                        updateProgressDialog.show();
                        String link = bUpdateMode.getDownLink();
                        BWebUtils.downloadFile(link, AppToolUtil.getDownloadAPKPath(MainView.this), new BWebUtils.WebDownloadListener() {
                            @Override
                            public void onProgress(int i) {

                            }

                            @Override
                            public void onSuccess(File file) {
                                toast("下载完成");
                                runOnUiThread(() -> {
                                    updateProgressDialog.dismiss();
                                    AppToolUtil.installAPK(AppToolUtil.getDownloadAPKPath(MainView.this).getAbsolutePath(), MainView.this);
                                });
                            }

                            @Override
                            public void onError(Exception e) {
                                runOnUiThread(() -> {
                                    updateProgressDialog.dismiss();
                                    toast("下载失败[" + e.toString() + "]");
                                });
                            }
                        });
                    });
                    mDialog.setNavigateBotton("忽略该版本", () -> sets.setIgnoreVersion(bUpdateMode.getAppVersion()));
                    mDialog.setNegativeBotton("稍后更新", null);
                    mDialog.show();
                }
            }

            @Override
            public void noNewVersion() {

            }

            @Override
            public void onError(Exception e) {
                Blog.e(TAG, e.toString());
            }
        });
    }


    @Override
    public void setHourlyWeatherData(HourlyAdapter data) {
        hourly_tongjitu_view.removeAllViews();
        for (HourlyAdapter.HourlyBean bean : data.getHourly()) {
            @SuppressLint("InflateParams") View view       = LayoutInflater.from(this).inflate(R.layout.hourly_item_view, null);
            ImageView                           icon       = view.findViewById(R.id.hourly_icon);
            MTextView                           tv_tem     = view.findViewById(R.id.hourly_tem);
            MTextView                           tv_weather = view.findViewById(R.id.hourly_weather);
            MTextView                           tv_time    = view.findViewById(R.id.hourly_time);
            icon.setImageBitmap(AppToolUtil.getweatherIcon(MainView.this, bean.getIcon()));
            tv_tem.setText(String.format("%s℃", bean.getTemp()));
            tv_weather.setText(bean.getText());
            String time = bean.getFxTime().substring(5);
            time = time.replace("T", " ").replace(" ", "\n").replace("+08:00", "");
            tv_time.setText(time);
            hourly_tongjitu_view.addView(view);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setMoonInfo(MoonAdapter data) {
        LinearLayout bg = find(R.id.main_moon_bg);
        if (sets.isHideExtraData()) {
            bg.setVisibility(View.GONE);
        }
        MoonAdapter.MoonPhaseBean bean = data.getBean();
        moon_icon.setImageBitmap(AppToolUtil.getweatherIcon(this, bean.getIcon()));
        moon_text.setText(bean.getName());
        moon_info.setText("月升:" + beliefTime(data.getMoonrise()) + "\n月落:" + beliefTime(data.getMoonset()) + "\n照明:" + bean.getIllumination() + "%");
        //语音
        if (sets.IsUsingSpeak()) {
            if (!sets.isDonated()) {
                if (isOpenedApp) {
                    String content = sets.getSpeakContent();
                    ttsUtils.speak(content + "。" + tts_stringBuilder.toString());
                    isOpenedApp = false;
                }
            } else {
                if (isOpenedApp) {
                    String      content = sets.getSpeakContent();
                    Set<String> strings = weatherDataBundle.keySet();
                    Log.d(TAG, "setAirNowData: " + content);
                    for (String key : strings) {
                        Log.d(TAG, "setAirNowData: " + key);
                        if (content.contains(key)) {
                            content = content.replace(key, weatherDataBundle.getString(key));
                        }
                    }
                    Log.d(TAG, "setAirNowData: " + content);
                    ttsUtils.speak(content);
                    isOpenedApp = false;
                }
            }
        }
        tts_stringBuilder.delete(0, tts_stringBuilder.length());
    }

    private String beliefTime(String time) {
        if (time != null) {
            return time.substring(time.indexOf("T") + 1, time.lastIndexOf("+"));
        }
        return "未知";
    }

    /**
     * @author BREEZE
     */
    @Override
    public void initListner() {
        main_share.setOnClickListener(onclick);
        main_city_history.setOnClickListener(onclick);
        main_open_drawer.setOnClickListener(onclick);
        main2_forecast.setOnClickListener(onclick);
        View view = find(R.id.main_more_city);
        view.setOnClickListener(onclick);
    }

    /**
     * @author BREEZE
     */
    @Override
    public void initHeConfig() {
        WeatherUtils.config();
    }


    private ImageView TopBackgroundImage, main2_weather_icon, drawer_top_pic, main_city_history;
    private MTextView           main_cityName;
    private MTextView           main_cityId;
    private MTextView           main_upcityName;
    private MTextView           main_xingzhebgName;
    private MTextView           main_areaTime;
    private MTextView           main_countryName;
    private MTextView           main2_weather_Name;
    private MTextView           main2_tem;
    private MTextView           main2_wind_direct;
    private MTextView           main2_wet;
    private MTextView           main_toolbar_city_name;
    private MTextView           main2_wind_speed;
    private MTextView           main2_yaqiang;
    private MTextView           main2_water_ml;
    private MTextView           main2_cansee;
    private MTextView           main2_bodytem_text;
    private MTextView           main2_clouds_text;
    private MTextView           main_week;
    private ScrollView          main_scrollview;
    private LinearLayout        main_relative_view;
    private LinearLayout        main_background_image_line;
    private LinearLayout        main_background_relativi;
    private LinearLayout        main2_forecast;
    private MainOnclickListener onclick;
    private LinearLayout        main2_environment_bg;
    private DrawerLayout        main_drawerlayout;
    private ImageView           main_open_drawer, main_share;
    private MTextView main_air_category;
    private MTextView main_air_pm25;
    private MTextView main_air_no2;
    private MTextView main_air_so2;
    private MTextView main_air_aqi;
    private MTextView main_air_co, main1_update;
    private MTextView main_air_co3, main_warning_text;
    private       LinearLayout       hourly_tongjitu_view;
    private       LinearLayout       weather_warning;
    private       NavigationView     navigationView;
    private       IMainViewPresenter presenter;
    private       RecyclerView       main_lifestyle_recyclerview;
    private final StringBuilder      tts_stringBuilder = new StringBuilder();
    private       boolean            isOpenedApp       = true;
    private       MTextView          moon_info;
    private       ImageView          moon_icon;
    private       MTextView          moon_text;
    private       AirWidgetView      airWidgetView;
    private       ProgressDialog     updateProgressDialog;

    @Override
    public void init() {
        TopBackgroundImage = find(R.id.main_top_background_imageview);
        main_cityName = find(R.id.main_city_name);
        main_cityId = find(R.id.main_city_id);
        main_upcityName = find(R.id.main_up_city_name);
        main_xingzhebgName = find(R.id.main_xingzheng_city_name);
        main_countryName = find(R.id.main_country_city_name);
        main_areaTime = find(R.id.main_areatime_city_name);
        main2_weather_Name = find(R.id.main2_weatherName);
        main2_weather_icon = find(R.id.main2_weather_icon);
        main_scrollview = find(R.id.activity_mainScrollView);
        main_relative_view = find(R.id.activity_mainRelativeLayout);
        main_toolbar_city_name = find(R.id.main_toolbat_city_name);
        main_city_history = find(R.id.main_more_city);
        main2_tem = find(R.id.main2_tem_text);
        main2_wind_direct = find(R.id.main2_wind_direct_n);
        main2_wet = find(R.id.main2_wet);
        main2_yaqiang = find(R.id.main2_yaqiang_text);
        main2_wind_speed = find(R.id.main2_windspeed_text);
        main2_water_ml = find(R.id.main2_water_ml_text);
        main2_cansee = find(R.id.main2_cansee_text);
        main2_bodytem_text = find(R.id.main2_bodytem_text);
        main2_clouds_text = find(R.id.main2_clouds_text);
        main_week = find(R.id.main_week);
        main_background_image_line = find(R.id.activity_main_1LinearLayout);
        main_background_relativi = find(R.id.activity_main_1RelativeLayout);
        main2_environment_bg = find(R.id.main2_environment_bg2);
        main2_forecast = find(R.id.main2_forecast);
        main_drawerlayout = find(R.id.mainDrawerLayout);
        main_open_drawer = find(R.id.main_open_drawer);
        main_share = find(R.id.main_share);
        main_air_aqi = find(R.id.main_air_aqi);
        main1_update = find(R.id.main1_now_update_time);
        hourly_tongjitu_view = find(R.id.main2_hourly_linearlayout);
        main_warning_text = find(R.id.main_warning_text);
        main_air_category = find(R.id.main_air_category);
        main_air_pm25 = find(R.id.main_air_pm25);
        main_air_no2 = find(R.id.main_air_no2);
        main_air_so2 = find(R.id.main_air_so2);
        main_air_co = find(R.id.main_air_co);
        main_air_co3 = find(R.id.main_air_co3);
        navigationView = find(R.id.main_navigationView);
        drawer_top_pic = navigationView.getHeaderView(0).findViewById(R.id.main_DrawerLayout_headImg);
        weather_warning = find(R.id.main2_warning);
        main_lifestyle_recyclerview = find(R.id.main_lifestyle_recyclerview);
        moon_text = find(R.id.main_moon_text);
        moon_icon = find(R.id.main_moon_icon);
        moon_info = find(R.id.main_moon_info);
        airWidgetView = find(R.id.main_air_widget);
    }

    public void showAnnotation(String annotation) {
        runOnUiThread(() -> {
            MDialog mDialog = new MDialog(this);
            mDialog.setTitle("公告");
            mDialog.setMessage(annotation);
            mDialog.setPositiveButton("确定", null);
            mDialog.setNegativeBotton("不再提醒", () -> sets.setAnnouncement(annotation));
            mDialog.show();
        });
    }

    @Override
    public void initData() {
        //初始化进度条提示
        updateProgressDialog = new ProgressDialog(this);
        updateProgressDialog.setTitle("提示");
        updateProgressDialog.setCancelable(false);
        updateProgressDialog.setMessage("正在下载中...");
        //初始化相关类
        ttsUtils = TTSUtils.getInstance(getApplicationContext());
        //NavigationView彩色图标
        navigationView.setItemIconTintList(null);
        navigationView.setNavigationItemSelectedListener(this);
        //设置背景
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        //初始化数据库
        databaseUtils = MyDatabaseUtils.getInstance(this);
        //初始化presenter
        this.presenter = new MainViewPresenter(this);
        //初始化点击事件
        onclick = new MainOnclickListener();
        //桌面长摁工具
        presenter.initShortCut();
        //初始化布局界面
        presenter.initLayoutWidget(TopBackgroundImage, main_background_relativi, main_background_image_line);
        //初始化标题栏样式
        presenter.initToolbarStyle(main_toolbar_city_name, main_relative_view, main_scrollview);
        //设置背景
        presenter.setMainBackground(TopBackgroundImage, drawer_top_pic);
        //初始化和风天气KEY
        initHeConfig();
        //获取城市数据
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, _REQUEST_LOCATION_PERMISSION_CODE);
        } else {
            if (sets.isAutoGetLocation()) {
                presenter.getCityInfoByLocation();
            } else {
                presenter.getCityInfo(sets.getDefaultCityCode());
            }
        }
        //注册广播
        broadcast = new MyMainBroadcast();
        IntentFilter filter = new IntentFilter(AppSettings._ACTION_UPDATE_MAINVIEW_BACKGROUND);
        registerReceiver(broadcast, filter);
        //检测通知是否打开
        //presenter.jumpToNotificationSettings();
        //发送更新桌面部件广播
        //显示公告
        presenter.getAnnouncement(sets);
    }

    private MyMainBroadcast broadcast;

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcast);
        ttsUtils.finish();
        super.onDestroy();
    }

    public static final String TAG = "MainView";

    private Bundle weatherNowBundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initData();
        initListner();
        checkHotFix();
    }

    private void checkHotFix() {
        BHotFixUtils.checkPatch((i, s, v) -> {
            File     patchStoragePath = BHotFixUtils.patchStoragePath;
            String[] list             = patchStoragePath.list();
            String   s1               = Arrays.toString(list);
            if (Integer.parseInt(v) > sets.getPatchVersion() || !s1.contains(s)) {
                if (i == 2) {
                    BAppUtils.uiExecute(() -> {
                        MDialog mDialog = new MDialog(MainView.this);
                        mDialog.setTitle("提示");
                        mDialog.setMessage("当前版本已经严重过时并且不再维护，请立即更新到新版本!");
                        mDialog.setCancelable(false);
                        mDialog.setPositiveButton("确定", () -> {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.parse(API._API_APK), "text/*");
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            startActivity(intent);
                        });
                        mDialog.show();
                    });
                } else if (i == 1 && sets.isHotFix()) {
                    AppToolUtil.deleteAllPatches();
                    BWebUtils.downloadFile(API._API_HOT_FIX_DIR + s, new File(BHotFixUtils.patchStoragePath + "/" + s), new BWebUtils.WebDownloadListener() {
                        @Override
                        public void onProgress(int i) {
                            Log.d(TAG, "onProgress: " + i);
                        }

                        @Override
                        public void onSuccess(File file) {
                            sets.setPatchVersion(Integer.parseInt(v));
                            toast("已安装新补丁，请重启应用");
                        }

                        @Override
                        public void onError(Exception e) {
                            toast("补丁下载失败[" + e.toString() + "]");
                        }
                    });
                }
            }
        });
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_change_city) {
            startActivityForResult(new Intent(MainView.this, SearchCityView.class), _SEARCH_CITY_REQUEST_CODE);
        } else if (itemId == R.id.menu_earthquake) {
            startActivityForResult(new Intent(MainView.this, EarthquakeActivity.class), _SEARCH_CITY_REQUEST_CODE);
        } else if (itemId == R.id.menu_typhoon) {
            startActivityForResult(new Intent(MainView.this, TyphoonInfoActivity.class), _SEARCH_CITY_REQUEST_CODE);
        } else if (itemId == R.id.menu_app_settings) {
            startActivity(new Intent(MainView.this, SettingsView.class));
        } else if (itemId == R.id.menu_about) {
            Intent intent_about = new Intent(MainView.this, AboutView.class);
            startActivity(intent_about);
        } else if (itemId == R.id.menu_more_tool) {
            startActivity(new Intent(MainView.this, MoreToolView.class));
        }
        return false;
    }

    class MainOnclickListener implements View.OnClickListener {
        @SuppressLint({"NonConstantResourceId", "SetTextI18n", "WrongConstant"})
        @Override
        public void onClick(View p1) {
            switch (p1.getId()) {
                case R.id.main_open_drawer:
                    if (main_drawerlayout.isDrawerOpen(Gravity.START)) {
                        main_drawerlayout.closeDrawer(Gravity.START);
                    } else {
                        main_drawerlayout.openDrawer(Gravity.START);
                    }
                    break;
                case R.id.main_share:
                    if (weatherNowBundle != null) {
                        Intent intent = new Intent(MainView.this, ShareWeatherView.class);
                        intent.putExtras(weatherNowBundle);
                        startActivity(intent);
                    } else {
                        toast("未获取到当前天气数据");
                    }
                    break;
                case R.id.main_more_city:
                    startActivityForResult(new Intent(MainView.this, CityHistory.class), _SEARCH_CITY_REQUEST_CODE);
                    break;
                case R.id.main2_forecast:
                    startActivity(new Intent(MainView.this, WeatherForecastView.class).putExtra("cityID", weatherNowBundle.getString("cityId")).putExtra("cityName", weatherNowBundle.getString("cityName")));
                    break;
                default:
                    Blog.e(TAG, "不存在这个控件");
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == _REQUEST_LOCATION_PERMISSION_CODE) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                toast("获取定位权限失败！");
                presenter.getCityInfo(sets.getDefaultCityCode());
            } else {
                presenter.getCityInfoByLocation();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private static final int _SEARCH_CITY_REQUEST_CODE         = 1;
    private static final int _REQUEST_LOCATION_PERMISSION_CODE = 2;

    @SuppressLint("WrongConstant")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == _SEARCH_CITY_REQUEST_CODE) {//搜索城市结果
            if (resultCode == 1) {
                //有数据
                String cityCode = data.getStringExtra("cityCode");
                if (cityCode != null && !cityCode.startsWith("CN")) {
                    cityCode = "CN" + cityCode;
                }
                sets.setDefaultCityCode(cityCode);
                presenter.getCityInfo(cityCode);
                if (main_drawerlayout.isDrawerOpen(Gravity.START)) {
                    main_drawerlayout.closeDrawer(Gravity.START);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //点击两次退出
    boolean isExit = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                finish();
                return true;
            } else {
                toast("再次操作就可以退出啦！");
                isExit = true;
                exitHandler.sendEmptyMessageDelayed(0, 2000);
                return false;
            }
        }
        return false;
    }

    Handler exitHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            isExit = false;
        }
    };

    class MyMainBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equalsIgnoreCase(SettingsStaticData._ACTION_UPDATE_MAINVIEW_BACKGROUND)) {
                presenter.setMainBackground(TopBackgroundImage, drawer_top_pic);
            } else if (action.equalsIgnoreCase(AppSettings._ACTION_UPDATE_DEFAULT_HEWEATHER_KEY)) {
                //初始化和风天气KEY
                initHeConfig();
                //获取城市数据
                if (ContextCompat.checkSelfPermission(MainView.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainView.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, _REQUEST_LOCATION_PERMISSION_CODE);
                } else {
                    if (sets.isAutoGetLocation()) {
                        presenter.getCityInfoByLocation();
                    } else {
                        presenter.getCityInfo(sets.getDefaultCityCode());
                    }
                }
            } else if (action.equalsIgnoreCase(AppSettings._ACTION_UPDATE_GET_CITY_METHOD)) {
                boolean permission = checkPermission(Manifest.permission.ACCESS_FINE_LOCATION);
                if (sets.isAutoGetLocation() && permission) {
                    presenter.getCityInfoByLocation();
                } else if (!permission) {
                    toast("请给予权限后重启应用");
                } else {
                    presenter.getCityInfo(sets.getDefaultCityCode());
                }
            }
        }
    }
}
